<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" ref="queryForm" :form="queryForm">

        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="用户名">
              <a-input v-decorator="['username',{ rules: [{ required: false}] }]" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="密码">
              <a-input v-decorator="['password',{ rules: [{ required: false}] }]" />
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="头像">
                <a-input v-decorator="['avatar',{ rules: [{ required: false}] }]" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="邮箱">
                <a-input v-decorator="['email',{ rules: [{ required: false}] }]" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="昵称">
                <a-input v-decorator="['nickName',{ rules: [{ required: false}] }]" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机">
                <a-input v-decorator="['mobile',{ rules: [{ required: false}] }]" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="备注信息">
                <a-input v-decorator="['note',{ rules: [{ required: false}] }]" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select placeholder="请选择" v-decorator="['statusEnable',{ rules: [{ required: false}] }]">
                  <a-select-option value="">请选择</a-select-option>
                  <a-select-option value="0">禁用</a-select-option>
                  <a-select-option value="1">正常</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="最后登录时间">
                <a-input v-decorator="['loginTime',{ rules: [{ required: false}] }]" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="handleSearchUmsAdmin">查询</a-button>
              <a-button style="margin-left: 8px" @click="handleSearchResetUmsAdmin">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" v-action:ums_umsAdmin_add icon="plus" @click="handleAddUmsAdmin">新建</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" v-action:ums_umsAdmin_delete @click="handleBatchDeleteUmsAdmin"><a-icon type="delete" />删除</a-menu-item>
          <!-- lock | unlock -->
          <a-menu-item key="2"><a-icon type="lock" />扩展</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- 列表  -->
    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :alert="{ show: true, clear: true }"
      :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
    >
      <template v-for="(col, index) in columns" v-if="col.scopedSlots" :slot="col.dataIndex" slot-scope="text">
        <div :key="index">
          <template>{{ text }}</template>
        </div>
      </template>
      <template slot="status" slot-scope="text">
        <div v-if="text==1">正常</div>
        <div v-if="text==0">禁用</div>
      </template>
      <span slot="action" slot-scope="text, record">
        <a @click="handleEditUmsAdmin(record)">编辑</a>
        <a-divider type="vertical" />
        <a-dropdown>
          <a class="ant-dropdown-link">
            更多 <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a href="javascript:;" @click="handleDetailUmsAdmin(record)" >详情</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" v-if="record.statusEnable==1" @click="handleDisableStatusUmsAdmin(record)">禁用</a>
              <a href="javascript:;" v-if="record.statusEnable==0" @click="handleDisableStatusUmsAdmin(record)">启用</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="handleDeleteUmsAdmin(record)">删除</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </s-table>
    <!--   编辑表单 -->
    <a-modal
      title="操作"
      :width="800"
      v-model="modelVisible"
      :confirmLoading="confirmLoading"
      @ok="handleSaveOrUpdateUmsAdmin"
    >
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="ID"
          validateStatus="success"
          hasFeedback >
          <a-input
            v-decorator="[ 'adminId',{ rules: [{ required: false, message: '主键' }] }]"
            disabled="disabled" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="用户名"
          hasFeedback >
          <a-input
            v-decorator="[ 'username',{ rules: [{ required: false, message: '用户名' }] }]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="密码"
          hasFeedback >
          <a-input
            v-decorator="[ 'password',{ rules: [{ required: false, message: '密码' }] }]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="头像"
          hasFeedback >
          <a-input
            v-decorator="[ 'avatar',{ rules: [{ required: false, message: '头像' }] }]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="邮箱"
          hasFeedback >
          <a-input
            v-decorator="[ 'email',{ rules: [{ required: false, message: '邮箱' }] }]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="昵称"
          hasFeedback >
          <a-input
            v-decorator="[ 'nickName',{ rules: [{ required: false, message: '昵称' }] }]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="手机"
          hasFeedback >
          <a-input
            v-decorator="[ 'mobile',{ rules: [{ required: false, message: '手机' }] }]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备注信息"
          hasFeedback >
          <a-input
            v-decorator="[ 'note',{ rules: [{ required: false, message: '备注信息' }] }]"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态"
        >
          <a-select
            v-decorator="['statusEnable',{ rules: [{ required: false, message: '请选择状态!' }] }]"
            placeholder="请选择状态"
          >
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="最后登录时间"
          hasFeedback >
          <a-input
            v-decorator="[ 'loginTime',{ rules: [{ required: false, message: '最后登录时间' }] }]"
          />
        </a-form-item>
        <a-divider />
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
  import { STable } from '@/components'
  import api from '@/api'
  import { deleteUmsAdmin, updateUmsAdmin, addUmsAdmin, batchDeleteUmsAdmin } from '@/api/umsAdminApi'

  export default {
    name: 'UmsAdminList',
    data () {
      return {
        description: '',
        editModelVisible: false,
        confirmLoading: false,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        form: this.$form.createForm(this, { name: 'entity_form' }),
        queryForm: this.$form.createForm(this, { name: 'query_form' }),
        editRecord: {},
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {
        },
        // 表头

        columns: [
          {
            title: '用户名',
            dataIndex: 'username',
            width: '100px',
            sorter: false,
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            title: '密码',
            dataIndex: 'password',
            width: '100px',
            sorter: false,
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            title: '头像',
            dataIndex: 'avatar',
            width: '100px',
            sorter: false,
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            title: '邮箱',
            dataIndex: 'email',
            width: '100px',
            sorter: false,
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            title: '昵称',
            dataIndex: 'nickName',
            width: '100px',
            sorter: false,
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            title: '手机',
            dataIndex: 'mobile',
            width: '100px',
            sorter: false,
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            title: '备注信息',
            dataIndex: 'note',
            width: '100px',
            sorter: false,
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            title: '状态',
            dataIndex: 'statusEnable',
            width: '100px',
            sorter: false,
            scopedSlots: { customRender: 'status' },
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            title: '最后登录时间',
            dataIndex: 'loginTime',
            width: '100px',
            sorter: false,
            // scopedSlots: { customRender: '' },
            needTotal: false
          },
          {
            table: '操作',
            dataIndex: 'action',
            width: '130px',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return this.$http.get(api.umsAdminUrl, {
            params: Object.assign(parameter, this.queryParam)
          }).then(res => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: []
      }
    },
    components: {
      STable
    },
    methods: {
      // 搜索查询
      handleSearchUmsAdmin () {
        this.queryParam = this.queryForm.getFieldsValue()
        this.loadData = parameter => {
          return this.$http.get(api.umsAdminUrl, {
            params: Object.assign(parameter, this.queryParam)
          }).then(res => {
            return res.data
          })
        }
        this.$refs.table.refresh()
      },
      // 搜索重置
      handleSearchResetUmsAdmin () {
        this.queryForm.resetFields()
      },
      handleChangeUmsAdmin (value, key, column, record) {
        record[column.dataIndex] = value
      },
      handleEditUmsAdmin (record) {
        this.editRecord = Object.assign({}, record)
        this.modelVisible = true
        this.$nextTick(() => {
          let values = this.form.getFieldsValue()
          for(let key in values) {
            values[key] = this.editRecord[key];
            this.form.setFieldsValue(values)
          }
        })
      },
      // 新增
      handleAddUmsAdmin () {
        this.editRecord = {}
        this.modelVisible = true
        this.form.resetFields();
      },
      // 批量删除
      handleBatchDeleteUmsAdmin () {
        // console.log('===============handleBatchDelete', this.selectedRowKeys)
        // console.log('===============handleBatchDelete', this.selectedRowKeys[0])
        let ids = this.selectedRowKeys
        let params = this.selectedRowKeys
        const that = this
        this.$confirm({
          title: '警告',
          content: `真的要批量删除 ${ids.length} 个吗?`,
          okText: '删除',
          okType: 'danger',
          cancelText: '取消',
          onOk () {
            // 在这里调用删除接口
            return new Promise((resolve, reject) => {
              batchDeleteUmsAdmin(params)
                .then(res => {
                  that.$refs.table.clearSelected()
                  that.$refs.table.refresh()
                  that.$notification['success']({
                    message: '提示',
                    description: res.msg || '删除成功',
                    duration: 8
                  })
                  resolve()
                }).catch((err) => {
                reject(err)
                that.$notification['error']({
                  message: '提示',
                  description: err.msg || '删除失败',
                  duration: 8
                })
              })
            }).catch(() => console.log('Oops errors!'))
          },
          onCancel () {
            console.log('Cancel')
          }
        })
      },
      edit (row) {
        row.editable = true
        // row = Object.assign({}, row)
      },
      // eslint-disable-next-line
      handleDeleteUmsAdmin (row) {
        const that = this
        this.$confirm({
          title: '警告',
          content: `真的要删除吗?`,
          okText: '删除',
          okType: 'danger',
          cancelText: '取消',
          onOk () {
            // 在这里调用删除接口
            return new Promise((resolve, reject) => {
              deleteUmsAdmin(row.adminId)
                .then(res => {
                  that.$refs.table.refresh()
                  that.$notification['success']({
                    message: '提示',
                    description: res.msg || '删除成功',
                    duration: 8
                  })
                  resolve()
                }).catch((err) => {
                reject(err)
                that.$notification['error']({
                  message: '提示',
                  description: err.msg || '删除失败',
                  duration: 8
                })
              })
            }).catch(() => console.log('Oops errors!'))
          },
          onCancel () {
            console.log('Cancel')
          }
        })
      },
      handleDetailUmsAdmin (row) {
        // console.log('============ handleDetail')
      },
      handleDisableStatusUmsAdmin (row) {
        const that = this
        let txt = row.statusEnable === 1 ? '禁用' : '启用'
        this.$confirm({
          title: '警告',
          content: `真的要${txt}吗?`,
          okText: txt,
          okType: 'danger',
          cancelText: '取消',
          onOk () {
            // 在这里调用更新接口
            return new Promise((resolve, reject) => {
              let params = { 'adminId': row.adminId,
                'statusEnable': row.statusEnable === 1 ? 0 : 1 }
              updateUmsAdmin(row.adminId, params)
                .then(res => {
                  that.$refs.table.refresh()
                  that.$notification['success']({
                    message: '提示',
                    description: res.msg || '操作成功',
                    duration: 8
                  })
                  resolve()
                }).catch((err) => {
                reject(err)
                that.$notification['error']({
                  message: '提示',
                  description: err.msg || '操作失败',
                  duration: 8
                })
              })
            }).catch(() => console.log('Oops errors!'))
          },
          onCancel () {
            console.log('Cancel')
          }
        })
      },
      // 更新、保存
      handleSaveOrUpdateUmsAdmin () {
        console.log('model data', this.editRecord)
        // this.confirmLoading = true;
        this.form.validateFields((err, values) => {
          if (err) {
            // this.confirmLoading = false;
            return;
          }
          console.log('Received values of form: ', values);
          this.editRecord = values
          this.confirmLoading = true;
          if (this.editRecord.adminId) {
            // 更新操作
            updateUmsAdmin(this.editRecord.adminId, this.editRecord)
              .then(res => {
                this.$notification['success']({
                  message: '提示',
                  description: res.msg || '操作成功',
                  duration: 8
                })
                this.form.resetFields();
                this.modelVisible = false;
                this.confirmLoading = false;
                this.$refs.table.refresh()
              })
              .catch((err) => {
                this.confirmLoading = false;
                this.$notification['error']({
                  message: '提示',
                  description: err.msg || '操作失败',
                  duration: 8
                })
              })
          }else {
            // 新增操作
            addUmsAdmin(this.editRecord)
              .then(res => {
                this.$notification['success']({
                  message: '提示',
                  description: res.msg || '操作成功',
                  duration: 8
                })
                this.form.resetFields();
                this.modelVisible = false;
                this.confirmLoading = false;
                this.$refs.table.refresh()
              })
              .catch((err) => {
                this.confirmLoading = false;
                this.$notification['error']({
                  message: '提示',
                  description: err.msg || '操作失败',
                  duration: 8
                })
              })
          }
        });
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      }
    }
  }
</script>

<style lang="less" scoped>
  .search {
    margin-bottom: 54px;
  }

  .fold {
    width: calc(100% - 216px);
    display: inline-block
  }

  .operator {
    margin-bottom: 18px;
  }

  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
</style>
